package br.urca.impl;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;

import br.urca.dao.FrequenciaHistDAO;
import br.urca.model.FrequenciaHist;
import br.urca.model.FrequenciaPK;

@Transactional
public class JPAFrequenciaHistDAO implements FrequenciaHistDAO {
	
	private EntityManager manager;
	
	public JPAFrequenciaHistDAO() {
		this(null);
	}
	
	@Inject
	public JPAFrequenciaHistDAO(EntityManager manager) {
		this.manager = manager;
	}

	@Override
	public List<FrequenciaHist> todos() {
		return this.manager.createQuery("SELECT f FROM FrequenciaHist f", FrequenciaHist.class)
				.getResultList();
	}

	@Override
	public List<FrequenciaHist> todos(FrequenciaPK frequenciaPK) {
		try {
			return this.manager.createQuery("SELECT f FROM FrequenciaHist f "
					+ "WHERE f.id.codOferta = :oferta "
					+ "AND f.id.codPedido = :pedido "
					+ "AND f.id.ano = :ano "
					+ "AND f.id.mes = :mes ", FrequenciaHist.class)
					.setParameter("oferta", frequenciaPK.getCodOferta())
					.setParameter("pedido", frequenciaPK.getCodPedido())
					.setParameter("ano", frequenciaPK.getAno())
					.setParameter("mes", frequenciaPK.getMes())
					.getResultList();
		} catch(Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public FrequenciaHist getObject(String oferta, String pedido, short ano,
			short mes, String matricula) {
		try {
			return this.manager.createQuery("SELECT f FROM FrequenciaHist f "
					+ "WHERE f.id.codOferta = :oferta "
					+ "AND f.id.codPedido = :pedido "
					+ "AND f.id.ano = :ano "
					+ "AND f.id.mes = :mes "
					+ "AND f.id.matricula = :matricula", FrequenciaHist.class)
					.setParameter("oferta", oferta)
					.setParameter("pedido", pedido)
					.setParameter("ano", ano)
					.setParameter("mes", mes)
					.setParameter("matricula", matricula)
					.getSingleResult();
		} catch(Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public void salvar(FrequenciaHist frequenciaHist) {
		if (frequenciaHist != null) {
			this.manager.merge(frequenciaHist);
		}
	}

	@Override
	public int getQtdFaltas(String matricula, String oferta, String pedido) {
		try {
			List<FrequenciaHist> mList = 
				this.manager.createQuery("SELECT f FROM FrequenciaHist f "
					+ "WHERE f.id.codOferta = :oferta "
					+ "AND f.id.codPedido = :pedido "
					+ "AND f.id.matricula = :matricula", FrequenciaHist.class)
					.setParameter("oferta", oferta)
					.setParameter("pedido", pedido)
					.setParameter("matricula", matricula)
					.getResultList();
			int retorno = 0;
			for (FrequenciaHist f: mList) {
				retorno += f.getAusencias();
			}
			return retorno;
		} catch(Exception e) {
			e.printStackTrace();
			return 0;
		} 
	}

}
